package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dao.CategoryDao;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao,Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    //根据id删除分类，删除之前要判断表关系
    @Override
    public void remove(Long id) {
        //查询当前要删除的分类是否关联菜品，如果关联就抛出异常
        LambdaQueryWrapper<Dish> dishlambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        dishlambdaQueryWrapper.eq(Dish::getCategoryId,id);

        int dishcount = dishService.count(dishlambdaQueryWrapper);
        if (dishcount > 0){
            //已经关联了菜品，需要抛出异常
            throw new CustomException("已经关联了其他菜品嗷，不阔以删除。");
        }

        //查询当前要删除的分类是否关联套餐，如果关联就抛出异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);

        int setmeal = setmealService.count(setmealLambdaQueryWrapper);
        if (setmeal > 0){
            //已经关联了套餐，需要抛出异常
            throw new CustomException("已经关联了其他套餐嗷，不阔以删除。");
        }

        //没有关联，正常删除
        super.removeById(id);
    }
}
